<?php

namespace common\models;

use Yii;
use common\models\Project;

/**
 * 资产包尽调评估立项信息
 * This is the model class for table "package_initiation".
 *
 * @property string $id
 * @property string $package_id
 * @property string $basic
 * @property string $seller_files
 * @property string $deal_method
 * @property string $partners
 * @property string $law
 * @property string $bargain
 * @property string $future_price_space
 * @property string $other_notes
 * @property string $reason
 * @property string $pass_date
 * @property string $leader
 * @property string $pre_evaluation
 * @property string $due_diligence
 * @property string $other_team_notes
 * @property string $price_detail
 * @property string $price_detail1
 * @property string $price_detail2
 * @property string $price_detail3
 * @property string $price_detail4
 * @property string $price_detail5
 * @property string $price_detail6
 * @property string $created_at
 * @property integer $lock_user
 * @property string $lock_timestamp
 */
class PackageInitiation extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'package_initiation';
    }

    /*关联项目表*/
    public function getPackage()
    {
        return $this->hasOne(Package::className(), ['id' => 'package_id']);
    }

    /*关联项目表*/
    public function getProject()
    {
        return $this->hasMany(Project::className(), ['package_id' => 'package_id'])->select('id');
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['package_id', 'lock_user'], 'integer'],
            [['basic', 'seller_files', 'deal_method', 'partners', 'law' ,'future_price_space', 'other_notes', 'reason',
                'pass_date', 'pre_evaluation', 'due_diligence', 'other_team_notes', 'price_detail',
                'price_detail1','price_detail2','price_detail3','price_detail4','price_detail5','price_detail6',
                'leader'], 'trim'],

            [['basic', 'seller_files', 'deal_method', 'partners', 'law', 'future_price_space', 'other_notes', 'reason',
                'pass_date', 'pre_evaluation', 'due_diligence', 'other_team_notes', 'price_detail',
                'price_detail1','price_detail2','price_detail3','price_detail4','price_detail5','price_detail6',
                'leader'], 'string'],

            //[['leader'], 'required'],
            [['created_at'], 'safe'],
            //[['leader', 'lock_timestamp'], 'string', 'max' => 255],
            [['lock_timestamp'], 'string', 'max' => 255],
            ['bargain', 'validateBargain'],
        ];
    }

    public function validateBargain()
    {
        if (!is_numeric($this->bargain) && $this->bargain !='' ) {
            $number = Package::set_number_format($this->bargain);
            if ($this->bargain != $number) {
                $this->addError('principal', '当前卖方报价（预估售价）格式不正确。');
            }
        }
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'package_id' => '资产包',
            'basic' => '基本情况',
            'seller_files' => '卖家提供的信息资料',
            'deal_method' => '资产成交期限和方式',
            'partners' => '当地共同处置资产包的合作伙伴情况',
            'law' => '当地司法环境对所立项目的法律支持',
            'bargain' => '当前卖方报价（预估售价）',
            'future_price_space' => '未来价格可谈判空间',
            'other_notes' => '其他需要说明的事项',
            'reason' => '申请立项的理由',
            'pass_date' => '立项通过时间',
            'leader' => '资产包负责人',
            'pre_evaluation' => '预评估人员',
            'due_diligence' => '尽调成员',
            'other_team_notes' => '团队其它说明',
            'price_detail' => '报价信息详情',
            'price_detail1' => '获取其他买家的信息、报价情况、工作进展情况',
            'price_detail2' => '采取通道方式成交的，明确通道主体及费用',
            'price_detail3' => '与卖家进行价格谈判，并初步确定成交价格、成交方式、成交时间及付款方式',
            'price_detail4' => '是否已经获得投资人和通道的收购承诺函',
            'price_detail5' => '资产包交接清单的确认，原件资料核对无误',
            'price_detail6' => '资产包存在的风险',
            'created_at' => '创建时间',
            'lock_user' => '上锁用户',
            'lock_timestamp' => '上锁时间',
        ];
    }

    /**
     * @param $id 主键
     * @param $package_id 资产包id
     * @param $changedAttributes 属性值
     * @param $userId 用户id
     * @param $module 资类包修改日志module
     * @param int $type 1为添加,2为修改，3为删除
     * @return array
     */
    public function setUpdateLog($id, $package_id, $changedAttributes, $userId, $module, $type)
    {
        $model = self::findOne((int)$id);
        $package = Package::findOne($package_id);
        if ($model === null || $package === null) {
            return array('state' => false, 'msg' => '数据不存在');
        }

        $attributeLabels = $this->attributeLabels();
        $intAttributeLabels = ['package_id', 'lock_user', 'leader', 'pre_evaluation', 'due_diligence'];
        $userInfo = (new UserModel())->getDepartmentUsersList();
        switch ($type) {
            //添加
            case 1:
                $data = $changedAttributes;
                if (!empty($data)) {
                    $log = '新增';
                    foreach ($data as $key => $value) {
                        if (in_array($key, $intAttributeLabels)) {
                            switch ($key) {
                                case 'package_id':
                                    $value = $package->title;
                                    break;
                                case 'lock_user':
                                    if ($value>0) {
                                        $value = $userInfo[$value]['description'] . '—' . $userInfo[$value]['realname'];
                                    }
                                    break;
                                case 'leader':
                                    $arr = explode(',', trim($value,','));
                                    $str = '';
                                    foreach ($arr as $v) {
                                        $str .= $userInfo[(int)$v]['realname'] .'，';
                                    }
                                    $value = mb_substr($str, 0, -1, 'utf-8');
                                    break;
                                case 'pre_evaluation':
                                    $arr = explode(',', trim($value,','));
                                    $str = '';
                                    foreach ($arr as $v) {
                                        $str .= $userInfo[(int)$v]['realname'] .'，';
                                    }
                                    $value = mb_substr($str, 0, -1, 'utf-8');
                                    break;
                                case 'due_diligence':
                                    $arr = explode(',', trim($value,','));
                                    $str = '';
                                    foreach ($arr as $v) {
                                        $str .= $userInfo[(int)$v]['realname'] .'，';
                                    }
                                    $value = mb_substr($str, 0, -1, 'utf-8');
                                    break;
                                default:
                            }
                        }
                        if ($attributeLabels[$key] != 'ID') {
                            $log .= "{$attributeLabels[$key]}：{$value}\n";
                        }
                    }
                }
                break;

            //编辑
            case 2:
                //判断数据是否发生改变
                $state = false;
                $data = array(); //修改后的数据
                foreach ($changedAttributes as $key => $value) {
                    if ($model->$key != $value) {
                        $data[$key] = $value;
                        $state = true;
                    }
                }

                if (!$state) {
                    $model->lock_user = null;
                    $model->lock_timestamp = null;
                    if ($model->save()) {
                        return array('state' => true, 'msg' => '保存成功');
                    } else {
                        return array('state' => false, 'msg' => '保存失败');
                    }
                    //return array('state' => false, 'msg' => '没有做任何修改');
                }

                if (!empty($data)) {
                    $log = '';
                    //$log = '修改ID：' . $id . ',';
                    //$log = '修改ID为' . $id . '的立项信息数据,';
                    foreach ($data as $key => $value) {
                        if (in_array($key, $intAttributeLabels)) {
                            switch ($key) {
                                case 'package_id':
                                    $value = $package->title;
                                    break;
                                case 'lock_user':
                                    if ($value>0) {
                                        $value = $userInfo[$value]['description'] . '—' . $userInfo[$value]['realname'];
                                    }
                                    break;
                                case 'leader':
                                    $arr = explode(',', trim($value,','));
                                    $str = '';
                                    if (!isset($arr) &&is_array($arr)) {
                                        foreach ($arr as $v) {
                                            $str .= $userInfo[(int)$v]['realname'] . '，';
                                        }
                                        $value = mb_substr($str, 0, -1, 'utf-8');
                                    }
                                    break;
                                case 'pre_evaluation':
                                    $arr = explode(',', trim($value,','));
                                    $str = '';
                                    if (!isset($arr) &&is_array($arr)){
                                        foreach ($arr as $v) {
                                            $str .= $userInfo[(int)$v]['realname'] .'，';
                                        }
                                        $value = mb_substr($str, 0, -1, 'utf-8');
                                    }
                                    break;
                                case 'due_diligence':
                                    $arr = explode(',', trim($value,','));
                                    $str = '';
                                    if (!isset($arr) &&is_array($arr)) {
                                        foreach ($arr as $v) {
                                            $str .= $userInfo[(int)$v]['realname'] . '，';
                                        }
                                    }
                                    $value = mb_substr($str, 0, -1, 'utf-8');
                                    break;
                                default;
                            }
                        }
                        $log .= "{$attributeLabels[$key]}：{$value}\n";
                    }
                }
                break;

            //删除
            case 3:
                //$log = "删除ID：{$id}，";
                $log = "删除记录，";
                break;
            break;
        }

        try {
            $time = date('Y-m-d H:i:s');
            $packageUpdateLog = new PackageUpdateLog();
            $module_title_array = $packageUpdateLog->getModuleArrayTitle();
            $packageUpdateLog->package_id = $package_id;
            $packageUpdateLog->module = $module_title_array[$module];
            $packageUpdateLog->created_at = $time;
            $packageUpdateLog->user_id = $userId;
            $packageUpdateLog->log = mb_substr($log, 0, -1, 'utf-8');

            $re1 = $packageUpdateLog->save();
            if (!$re1) {
                throw new Exception('资产包立项信息日志添加失败');
            }

            return array('state' => true, 'msg' => '添加资产包修改日志成功');
        } catch (\Exception $e) {
            $message = $e->getMessage();
            return array('state' => false, 'msg' => $message);
        } catch (\Throwable $e) {
            $message = $e->getMessage();
            return array('state' => false, 'msg' => $message);
        }
    }

}
